import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { Gateway } from '../../entity/firmware/gateway.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';
// import { Class } from '../../entity/firmware/class.entity'
import { WristbandAdv } from '@entity/firmware/wristband_adv.entity';
interface SleepData {
  sleep_duration: number; // 总睡眠时长（分钟）
  wake_up_time: string; // 起床时间
  bed_time: string; // 入睡时间
  deep_sleep_duration: number; // 深睡时长（分钟）
  light_sleep_duration: number; // 浅睡时长（分钟）
}
function calculateSleepData(result: any[]): SleepData {
  let sleepStart: Date | null = null;
  let wakeUpTime: Date | null = null;
  let totalSleep = 0;
  let deepSleep = 0;
  let lightSleep = 0;
  let lastState = 'awake';

  result.forEach((item) => {
    const { hr, acc_x, acc_y, acc_z, hrv, time } = item;

    // 确保日期有效
    const timestamp = new Date(time);
    if (isNaN(timestamp.getTime())) {
      // console.warn(`Invalid date: ${time}`);
      return; // 跳过无效日期的记录
    }

    const movement = Math.sqrt(acc_x ** 2 + acc_y ** 2 + acc_z ** 2);

    let currentState: 'awake' | 'light_sleep' | 'deep_sleep';

    if (hr < 50 && hrv > 40 && movement < 0.05) {
      currentState = 'deep_sleep';
    } else if (hr < 60 && movement < 0.2) {
      currentState = 'light_sleep';
    } else {
      currentState = 'awake';
    }

    if (currentState !== 'awake') {
      if (!sleepStart) sleepStart = timestamp;
      totalSleep += 1; // 假设数据是按 1 分钟间隔存储的
      if (currentState === 'deep_sleep') deepSleep += 1;
      if (currentState === 'light_sleep') lightSleep += 1;
    } else {
      if (lastState !== 'awake') {
        wakeUpTime = timestamp;
      }
    }

    lastState = currentState;
  });

  return {
    sleep_duration: totalSleep,
    wake_up_time: wakeUpTime ? wakeUpTime.toISOString() : '',
    deep_sleep_duration: deepSleep,
    light_sleep_duration: lightSleep,
    bed_time: sleepStart ? sleepStart.toISOString() : ''  // 添加 bed_time
  };
}

@Provide()
export class GatewayWristbandService {
  @InjectEntityModel(Gateway)
  gatewayRepo: Repository<Gateway>;
  @InjectEntityModel(WristbandAdv)
  wristbandAdvRepo: Repository<WristbandAdv>
  @InjectEntityModel(WristbandAdv)
  wristbandAdvModel: Repository<WristbandAdv>;

  // **创建网关**
  async createGateway(data: Partial<Gateway>) {
    const gateway = this.gatewayRepo.create(data);
    return await this.gatewayRepo.save(gateway);
  }

  // **获取所有网关**
  async getAllGateways(params) {
    const { mac, version_bin, pageSize, pageNum } = params
    const query = this.gatewayRepo.createQueryBuilder('gateway')
      .leftJoinAndSelect('gateway.class', 'class') // 关联 class
      .leftJoinAndSelect('class.school', 'school')
    // .where('edgroup.deleted != :deleted', { deleted: true });
    if (mac) query.andWhere('gateway.mac LIKE :mac', { mac: `%${mac}%` });
    if (version_bin) query.andWhere('gateway.version_bin LIKE :version_bin', { version_bin: `%${version_bin}%` });
    if (pageSize && pageNum) {
      query.skip((pageNum - 1) * pageSize).take(pageSize);
    }
    // 按时间降序排列
    query.orderBy('gateway.time', 'DESC');
    // 查询总数 count
    const total = await query.getCount();
    // return await this.gatewayRepo.find({ relations: ['class'] }); // 加载关联的班级
    // 返回数据
    return {
      total,
      data: await query.getMany(),
    };
  }

  // 获取所有网关_手环数量(gateway 表)
  async getAllGateways_Wb(queryParams) {
    // 检查分页参数
    const page = parseInt(queryParams.page, 10) || 1; // 默认第 1 页
    const pageSize = parseInt(queryParams.pageSize, 10) || 10; // 默认每页 10 条
    console.log('queryParams', queryParams)
    let queryAll = this.gatewayRepo.createQueryBuilder('gateway');
    // 设置分页
    const skip = (page - 1) * pageSize;  // 计算跳过的记录数
    const take = pageSize; // 设置每页返回的记录数
    // if (queryParams.last_report_time) {
    //   queryAll.andWhere('gateway.last_report_time = :last_report_time', { last_report_time: queryParams.last_report_time });
    // }
    if (queryParams.mac) {
      queryAll.andWhere('gateway.mac = :mac', { mac: queryParams.mac });
    }
    // 添加分页到查询
    queryAll.skip(skip).take(take);
    let result = await queryAll.getMany() as any;

    return result;




    //   // queryParams.mac = queryParams.mac || '30:ed:a0:26:cd:0c'
    //   //  queryParams.date = queryParams.date || new Date()
    //   // 基础查询
    //   let query = `
    //     SELECT
    //       wba.gw_mac, 
    //       MAX(wba.time) AS last_adv_time,
    //       COUNT(wba.mac) AS count ,
    //       g.* -- @todo 改成需要的网关表的字段
    //     FROM
    //        wristband_adv wba left join gateway g on g.mac=wba.gw_mac
    //        WHERE 1=1
    //        ${queryParams.mac ? 'AND gw_mac = ?' : ''}
    //        ${queryParams.date ? 'AND wba.time = ?' : ''}
    //     GROUP BY wba.time
    //     ORDER BY wba.time DESC
    //     LIMIT ? OFFSET ?
    //   `;

    // //   let query = `
    // //   SELECT
    // //     wba.gw_mac, 
    // //     MAX(wba.time) AS last_adv_time,
    // //     COUNT(wba.mac) AS wb_cnt ,
    // //     g.* 
    // //   FROM wristband_adv wba left join gateway g on g.mac=wba.gw_mac
    // //      WHERE 1=1
    // //      ${queryParams.mac ? 'AND gw_mac = ?' : ''}
    // //      ${queryParams.date ? 'AND wba.time = ?' : ''}
    // // GROUP BY wba.time
    // // ORDER BY wba.time DESC
    // // limit 50
    // // `;

    //   // 动态构建参数
    //   const params: any[] = [];
    //   if (queryParams.mac) {
    //     params.push(queryParams.mac);
    //   }
    //   if (queryParams.date) {
    //     params.push(queryParams.date);
    //   }
    //   params.push(pageSize, (page - 1) * pageSize); // 分页参数

    //   try {
    //     const result = await this.gatewayRepo.query(query, params);
    //     console.log('Query result:', result);
    //     return result;
    //   } catch (error) {
    //     console.error('Error fetching wristband count:', error);
    //     throw error;
    //   }
  }



  // **根据 MAC 地址获取网关**
  async getGatewayByMac(mac: string) {
    const query = this.gatewayRepo.createQueryBuilder('gateway')
      .leftJoinAndSelect('gateway.class', 'class') // 关联 class
      .leftJoinAndSelect('class.school', 'school')
    if (mac) query.andWhere('gateway.mac = :mac', { mac });
    let result = await query.getMany()
    // console.log('query', result[0])
    return result[0];
  }


  // **根据 MAC 地址获取网关及手环**
  async getGatewayByMac_Wb(queryParams) {
    console.log(2222, queryParams)
    const query = this.wristbandAdvModel.createQueryBuilder('wristband_adv');
    let { date, wb_mac, gw_mac, pageNum, pageSize } = queryParams;

    // 设置分页
    const skip = (pageNum - 1) * pageSize;  // 计算跳过的记录数
    const take = pageSize; // 设置每页返回的记录数
    console.log(11111, date, gw_mac, wb_mac, pageNum, pageSize)
    if (wb_mac) {
      // 小写转大写 并启用模糊查询
      wb_mac = wb_mac.toUpperCase();
      query.andWhere('UPPER(wristband_adv.mac) LIKE UPPER(:mac)', { mac: `%${wb_mac}%` });
    }
    if (gw_mac) {
      query.andWhere('wristband_adv.gw_mac = :gw_mac', { gw_mac: gw_mac });
    }
    if (date) {
      query.andWhere('wristband_adv.time BETWEEN :start AND :end', {
        start: `${date[0]}`,
        end: `${date[1]}`,
      });
    }
    query.orderBy('wristband_adv.time', 'DESC');
    // 添加分页到查询
    query.skip(skip).take(take);
    let result = await query.getMany() as any;
    // 计算睡眠数据
    const sleepStats = calculateSleepData(result);

    result.forEach((item) => {
      // 赋值计算出的睡眠数据
      item.sleep_duration = sleepStats.sleep_duration;
      item.wake_up_time = sleepStats.wake_up_time;
      item.bed_time = sleepStats.bed_time;
      item.deep_sleep_duration = sleepStats.deep_sleep_duration;
      item.light_sleep_duration = sleepStats.light_sleep_duration;
    });

    // 返回分页后的结果
    const total = await query.getCount(); // 获取总记录数
    return {
      data: result,
      total,  // 返回总记录数
      pageNum,  // 当前页码
      pageSize,  // 每页条数
    };
  }


  // **更新网关信息**
  async updateGateway(mac: string, updateData: Partial<Gateway>) {
    const gateway = await this.getGatewayByMac(mac);
    if (!gateway) return null;

    Object.assign(gateway, updateData);
    return await this.gatewayRepo.save(gateway);
  }

  // **删除网关**
  async deleteGateway(mac: string) {
    const result = await this.gatewayRepo.delete(mac);
    return result.affected > 0;
  }
}
